import type { GameRoomConfig } from '../data/GameRoomConfig';
import type { GameRoomPlayer } from '../data/GameRoomPlayer';

/**
 * 参数验证器类
 * 提供各种参数和类型的验证方法，特别针对JavaScript开发者使用时的类型安全性检查
 */
export class Validator {
  /**
   * 验证房间配置参数
   * @param config 房间配置
   * @throws {Error} 当参数不符合要求时抛出错误
   */
  public static validateRoomConfig(
    config: any
  ): asserts config is GameRoomConfig {
    if (typeof config !== 'object' || config === null) {
      throw new Error('Room config must be an object');
    }

    if (config.id !== undefined && typeof config.id !== 'string') {
      throw new Error('Room id must be a string');
    }

    if (config.players !== undefined && !Array.isArray(config.players)) {
      throw new Error('Room players must be an array');
    }

    if (
      config.allowMultiRoom !== undefined &&
      typeof config.allowMultiRoom !== 'boolean'
    ) {
      throw new Error('Room allowMultiRoom must be a boolean');
    }

    if (
      config.allowPlayerJoin !== undefined &&
      typeof config.allowPlayerJoin !== 'boolean'
    ) {
      throw new Error('Room allowPlayerJoin must be a boolean');
    }

    if (
      config.allowPlayerLeave !== undefined &&
      typeof config.allowPlayerLeave !== 'boolean'
    ) {
      throw new Error('Room allowPlayerLeave must be a boolean');
    }

    if (
      config.maxPlayerCount !== undefined &&
      typeof config.maxPlayerCount !== 'number'
    ) {
      throw new Error('Room maxPlayerCount must be a number');
    }
  }

  /**
   * 验证玩家信息参数
   * @param player 玩家信息
   * @throws {Error} 当参数不符合要求时抛出错误
   */
  public static validatePlayer(player: any): asserts player is GameRoomPlayer {
    if (typeof player !== 'object' || player === null) {
      throw new Error('Player must be an object');
    }

    if (typeof player.userId !== 'string') {
      throw new Error('Player userId must be a string');
    }

    if (player.name !== undefined && typeof player.name !== 'string') {
      throw new Error('Player name must be a string');
    }
  }

  /**
   * 验证玩家ID参数
   * @param userId 玩家ID
   * @throws {Error} 当参数不符合要求时抛出错误
   */
  public static validateUserId(userId: any): asserts userId is string {
    if (typeof userId !== 'string') {
      throw new Error('User ID must be a string');
    }
  }

  /**
   * 验证房间ID参数
   * @param roomId 房间ID
   * @throws {Error} 当参数不符合要求时抛出错误
   */
  public static validateRoomId(roomId: any): asserts roomId is string {
    if (typeof roomId !== 'string') {
      throw new Error('Room ID must be a string');
    }
  }

  /**
   * 验证玩家数组参数
   * @param userIds 玩家ID数组
   * @throws {Error} 当参数不符合要求时抛出错误
   */
  public static validateUserIds(userIds: any): asserts userIds is string[] {
    if (!Array.isArray(userIds)) {
      throw new Error('User IDs must be an array');
    }

    userIds.forEach((userId, index) => {
      if (typeof userId !== 'string') {
        throw new Error(`User ID at index ${index} must be a string`);
      }
    });
  }
}
